package com.wyu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CheckLoginFilter",value = "/*")
public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.判断是否是登录页面，注册界面，或者登录注册相关的servlet，如果是则放行
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 获取用户访问的uri
        String uri = request.getRequestURI();

        //注意过滤器,会过滤图片，js，css文件，所以这些文件也要放行
        if(uri.contains("/index.jsp")
                ||uri.contains("/register.jsp")
                ||uri.contains("/LoginServlet")
                ||uri.contains("/RegisterServlet")
                ||uri.contains("/js/")
                ||uri.contains("/easyui/")
                ||uri.contains("/css/")){
            //放行
            chain.doFilter(req, resp);
        }else {
            //2.如果不是，从session中获取用户，就判断这个用户是否存在
            Object yg = request.getSession().getAttribute("yg");
            if (yg!=null){
                //4.如果没有登录则要跳转到登录界面，如果登录了就可以直接放行
                //放行
                chain.doFilter(req, resp);
            }else {
                //3.如果存在说明用户已经登录，如果不存在说明用户没有登录,跳转到登录界面
                response.sendRedirect("index.jsp");
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
